package com.bjpowernode.mvc.service.Impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjpowernode.common.client.RedisClient;
import com.bjpowernode.common.consts.Keys;
import com.bjpowernode.db.domain.BidInfo;
import com.bjpowernode.db.domain.ProductInfo;

import com.bjpowernode.mvc.model.dto.statics.AppStaticsDTO;
import com.bjpowernode.mvc.service.BaseService;
import com.bjpowernode.mvc.service.inter.StaticService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class StaticServiceImpl extends BaseService implements StaticService {


    /*从redis获取数据
     *  1.从redis查询数据
     *  2.redis有数据,转换为appstaticsDTO返回给controller
     *  3.redis没有数据,从数据库中查询,将查询后的数据存到redis中,返回数据给controller*/

    @Resource
    private RedisClient redisClient;

    @Override
    public  AppStaticsDTO queryAppInfo() {   //synchronized,同步.线程

        AppStaticsDTO dto=null;
        //1.从redis查询数据,存入到redis是json
        String strJson=redisClient.getStr(Keys.STATICS_INFO);
        if (StrUtil.isNotBlank(strJson)){
           dto = JSONUtil.toBean(strJson, AppStaticsDTO.class);
        }else {
            synchronized(this){
                //没有数据,从数据库里查询
                 strJson=redisClient.getStr(Keys.STATICS_INFO);
                if (StrUtil.isBlank(strJson)) {
                    dto = getAppStaticsInfoFromDB();

                    //dto-json存入到redis
                    redisClient.addStr(Keys.STATICS_INFO, JSONUtil.toJsonStr(dto), 120);
                }else {
                    dto = JSONUtil.toBean(strJson, AppStaticsDTO.class);

                }
            }
          }
            return dto;
    }


    //从数据库查询三项统计数据...

    private AppStaticsDTO getAppStaticsInfoFromDB() {
        //注意写sql语句的时候,务必写别名

        //注册用户数量.
        Long userCount = userMapper.selectCount(null);

        //累计成交的金额
        QueryWrapper<BidInfo> wrapper = new QueryWrapper<>();
        wrapper.select("IFNULL(sum(bid_money),0) as bid_money");
        BigDecimal allBigMoney = bidInfoMapper.selectOne(wrapper).getBidMoney();


        //3.产品利率平均值
        QueryWrapper<ProductInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("round(IFNULL(avg(rate),0),2) as rate");
        BigDecimal productAvgRate = productInfoMapper.selectOne(queryWrapper).getRate();

        return new AppStaticsDTO(userCount, allBigMoney, productAvgRate);
    }


}
